locals {
  rdshost   = data.terraform_remote_state.rds.outputs.rds_info.myapp.rds_ip
  redishost = data.terraform_remote_state.dcs.outputs.redis_info.myapp.redis_ip
}

resource "null_resource" "init_nacos_db" {
  provisioner "local-exec" {
    interpreter = ["bash", "-c"]
    environment = {
      rds_adminuser = var.rds_adminuser
      rds_adminpwd  = var.rds_adminpwd
      rds_nacosPwd  = var.rds_nacosPwd
      rds_host      = local.rdshost
    }
    command = <<EOF
      #!/bin/bash
      envsubst < ./nacos.sql.tmp > ./nacos.sql
      mysql -u'${rds_adminuser}' -p'${rds_adminpwd}' -h'${rds_host}'  < ./nacos.sql
    EOF
  }
}


resource "kubernetes_namespace" "nacos" {
  provider = kubernetes.cce-myapp-dev
  metadata {
    name = var.nacos_namespace
  }
}

resource "kubernetes_secret" "repo" {
  provider = kubernetes.cce-myapp-dev
  metadata {
    name      = var.repo_name
    namespace = kubernetes_namespace.nacos.id
  }

  type = "kubernetes.io/dockerconfigjson"

  data = {
    ".dockerconfigjson" = jsonencode({
      auths = {
        "${var.registry_server}" = {
          "username" = var.registry_user
          "password" = var.registry_pass
          "auth"     = base64encode("${var.registry_user}:${var.registry_pass}")
        }
      }
    })
  }
}

resource "kubernetes_service" "nacos-cluster" {
  provider = kubernetes.cce-myapp-dev
  metadata {
    name      = var.nacos_svc
    namespace = kubernetes_namespace.nacos.id
  }
  spec {
    type       = "ClusterIP"
    cluster_ip = "None"
    port {
      name        = "server"
      port        = 8848
      target_port = 8848
    }
    port {
      name        = "client-rpc"
      port        = 9848
      target_port = 9848
    }
    port {
      name        = "raft-rpc"
      port        = 9849
      target_port = 9849
    }
    port {
      name        = "old-raft-rpc"
      port        = 7848
      target_port = 7848
    }
    selector = {
      app = var.nacos_name
    }
  }
}

resource "kubernetes_service" "nacos_nodeport" {
  provider = kubernetes.cce-myapp-dev
  metadata {
    name      = "nacos-nodeport"
    namespace = kubernetes_namespace.nacos.id
  }
  spec {
    type = "NodePort"
    port {
      name        = "nacos-nodeport-8848"
      port        = 8848
      target_port = 8848
      node_port   = 31014
    }
    port {
      name        = "nacos-nodeport-9848"
      port        = 9848
      target_port = 9848
      node_port   = 31015
    }
    selector = {
      app = var.nacos_name
    }
  }
}

resource "kubernetes_config_map" "nacos" {
  provider = kubernetes.cce-myapp-dev
  metadata {
    name      = "nacos-cm"
    namespace = kubernetes_namespace.nacos.id
  }

  data = {
    "mysql.host"     = var.rds_host
    "mysql.db"       = var.rds_nacosDb
    "mysql.port"     = var.rds_port
    "mysql.user"     = var.rds_nacosUser
    "mysql.password" = var.rds_nacosPwd
  }
}


resource "kubernetes_stateful_set" "nacos" {
  provider = kubernetes.cce-myapp-dev
  metadata {
    name      = var.nacos_name
    namespace = kubernetes_namespace.nacos.id
    labels = {
      app                               = var.nacos_name
      "kubernetes.io/cluster-service"   = "true"
      "addonmanager.kubernetes.io/mode" = "Reconcile"
    }
  }

  spec {
    service_name           = "nacos-headless"
    replicas               = 3
    revision_history_limit = 5
    selector {
      match_labels = {
        app = var.nacos_name
      }
    }
    template {
      metadata {
        labels = {
          app = var.nacos_name
        }
        annotations = {
          "pod.alpha.kubernetes.io/initialized" = "true"
        }
      }
      spec {
        image_pull_secrets {
          name = kubernetes_secret.repo.metadata[0].name
        }
        container {
          name              = var.nacos_name
          image             = var.nacos_image
          image_pull_policy = "IfNotPresent"
          port {
            name           = "server"
            container_port = 8848
          }
          port {
            name           = "client-rpc"
            container_port = 9848
          }
          port {
            name           = "raft-rpc"
            container_port = 9849
          }
          port {
            name           = "old-raft-rpc"
            container_port = 7848
          }
          resources {
            requests = {
              cpu    = "200m"
              memory = "256Mi"
            }
            limits = {
              cpu    = "2000m"
              memory = "2048Mi"
            }
          }
          liveness_probe {
            http_get {
              path = "/nacos/v1/ns/operator/metrics"
              port = 8848
            }
            initial_delay_seconds = 60
            timeout_seconds       = 5
          }
          /* readiness_probe {
            http_get {
              path = "/nacos/v1/ns/operator/metrics"
              port = 8848
            }
            initial_delay_seconds = 60
            timeout_seconds       = 5
          } */
          env {
            name = "MYSQL_SERVICE_HOST"
            value_from {
              config_map_key_ref {
                name = kubernetes_config_map.nacos.metadata[0].name
                key  = "mysql.host"
              }
            }
          }
          env {
            name = "MYSQL_SERVICE_DB_NAME"
            value_from {
              config_map_key_ref {
                name = kubernetes_config_map.nacos.metadata[0].name
                key  = "mysql.db"
              }
            }
          }
          env {
            name = "MYSQL_SERVICE_PORT"
            value_from {
              config_map_key_ref {
                name = kubernetes_config_map.nacos.metadata[0].name
                key  = "mysql.port"
              }
            }
          }
          env {
            name = "MYSQL_SERVICE_USER"
            value_from {
              config_map_key_ref {
                name = kubernetes_config_map.nacos.metadata[0].name
                key  = "mysql.user"
              }
            }
          }
          env {
            name = "MYSQL_SERVICE_PASSWORD"
            value_from {
              config_map_key_ref {
                name = kubernetes_config_map.nacos.metadata[0].name
                key  = "mysql.password"
              }
            }
          }
          env {
            name  = "SPRING_DATASOURCE_PLATFORM"
            value = "mysql"
          }
          env {
            name  = "MODE"
            value = "cluster"
          }
          env {
            name  = "NACOS_REPLICAS"
            value = "3"
          }
          env {
            name  = "NACOS_SERVER_PORT"
            value = "8848"
          }
          env {
            name  = "PREFER_HOST_MODE"
            value = "hostname"
          }
          env {
            name  = "NACOS_SERVERS"
            value = "${var.nacos_name}-0.nacos-headless.${var.nacos_namespace}.svc.cluster.local:8848  ${var.nacos_name}-1.nacos-headless.${var.nacos_namespace}.svc.cluster.local:8848  ${var.nacos_name}-2.nacos-headless.${var.nacos_namespace}.svc.cluster.local:8848"
          }
          env {
            name  = "NACOS_AUTH_ENABLE"
            value = "false"
          }
          env {
            name  = "NACOS_AUTH_SYSTEM_TYPE"
            value = "nacos"
          }
          env {
            name  = "NACOS_AUTH_IDENTITY_KEY"
            value = "cFNLTlQ1MlNqd1VTczVkb1d1UnVnRDJheGJ5YlhBSDlx"
          }
          env {
            name  = "NACOS_AUTH_IDENTITY_VALUE"
            value = "Z1NVVDd5OTdqS0xzUTJ6NVB5ZmxUU0RFNldwb0lfazIzRXZOTmdFeWdtTQ=="
          }
          env {
            name  = "NACOS_AUTH_TOKEN"
            value = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjpbeyJuYWNvcyI6Im5hY29zIn1dLCJpYXQiOjE2ODk0MDI3NTEsImV4cCI6MjAwNDkOTU5OSwiYXVkIjoiIiwiaXNzIjoiIiwic3ViIjoiIn0.eT1sbXICdlJjQB_iu5q8tM8j5XlSZGoG5YPt2N5CLOc"
          }
        }
      }
    }
  }
}
